{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vmQmHoy-5cAh"
   },
   "source": [
    "# Notion Workspace Assistant with PraisonAIAgents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WOow52NM5dmh"
   },
   "source": [
    "This notebook demonstrates how to interact with your Notion workspace using PraisonAIAgents in Google Colab. You can read, search, and update Notion pages with natural language queries, leveraging agentic tools for seamless document management—all within a notebook environment."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "TlnFAv9P_lGL"
   },
   "source": [
    "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Programming_Code_Analysis_Agents/Notion_Workspace_Assistant.ipynb)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "zMn7hUGZ5hn5"
   },
   "source": [
    "# Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "U6X3lKAu6iU3"
   },
   "outputs": [],
   "source": [
    "!pip install praisonaiagents openai requests --quiet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4_96-D7z6lrC"
   },
   "source": [
    "# Set Up Key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "id": "kltUFVIW6rEO"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# Set your Notion and OpenAI API keys here\n",
    "NOTION_API_KEY = \"ntn_..\"  # <-- Replace with your actual Notion integration token\n",
    "OPENAI_API_KEY = \"sk-proj-_..\"  # <-- Replace with your actual OpenAI API key\n",
    "\n",
    "# Set environment variables for downstream libraries\n",
    "os.environ[\"NOTION_API_KEY\"] = NOTION_API_KEY\n",
    "os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "FOLTBEXu635I"
   },
   "source": [
    "# Tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "fLWxSASM5jlU"
   },
   "outputs": [],
   "source": [
    "from praisonaiagents import Agent\n",
    "import requests\n",
    "from IPython.display import display, Markdown"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KN_Sxha37EQ0"
   },
   "source": [
    "# Custom Tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "id": "WWxcfO9L7Fsu"
   },
   "outputs": [],
   "source": [
    "def notion_read_page_tool(page_id: str, notion_token: str) -> str:\n",
    "    \"\"\"\n",
    "    Custom tool to read the content of a Notion page using the Notion API.\n",
    "    \"\"\"\n",
    "    url = f\"https://api.notion.com/v1/blocks/{page_id}/children\"\n",
    "    headers = {\n",
    "        \"Authorization\": f\"Bearer {notion_token}\",\n",
    "        \"Notion-Version\": \"2022-06-28\"\n",
    "    }\n",
    "    response = requests.get(url, headers=headers)\n",
    "    if response.ok:\n",
    "        data = response.json()\n",
    "        blocks = data.get(\"results\", [])\n",
    "        content = []\n",
    "        for block in blocks:\n",
    "            block_type = block.get(\"type\", \"\")\n",
    "            text = \"\"\n",
    "            if block_type == \"paragraph\":\n",
    "                text = block.get(\"paragraph\", {}).get(\"text\", [])\n",
    "                if text:\n",
    "                    text = text[0].get(\"plain_text\", \"\")\n",
    "            elif block_type == \"heading_1\":\n",
    "                text = block.get(\"heading_1\", {}).get(\"text\", [])\n",
    "                if text:\n",
    "                    text = \"# \" + text[0].get(\"plain_text\", \"\")\n",
    "            elif block_type == \"heading_2\":\n",
    "                text = block.get(\"heading_2\", {}).get(\"text\", [])\n",
    "                if text:\n",
    "                    text = \"## \" + text[0].get(\"plain_text\", \"\")\n",
    "            elif block_type == \"heading_3\":\n",
    "                text = block.get(\"heading_3\", {}).get(\"text\", [])\n",
    "                if text:\n",
    "                    text = \"### \" + text[0].get(\"plain_text\", \"\")\n",
    "            if text:\n",
    "                content.append(text)\n",
    "        return \"\\n\".join(content) if content else \"No readable content found on this page.\"\n",
    "    else:\n",
    "        return f\"Failed to fetch page content: {response.text}\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ebuhw9z27Nae"
   },
   "source": [
    "# YAML Prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "eMjDDjzO7Pf3",
    "outputId": "b935f96d-f147-44de-80ea-7f75d23f9e7b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "agent_instructions: |\n",
      "  You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
      "  - Provide clear, organized summaries of page content.\n",
      "  - Use the Notion API to fetch and display information.\n",
      "  - If a page cannot be read, explain the issue clearly.\n",
      "\n",
      "tools:\n",
      "  - name: notion_read_page_tool\n",
      "    description: >\n",
      "      Reads the content of a Notion page using its page ID and the user's Notion integration token.\n",
      "    parameters:\n",
      "      - name: page_id\n",
      "        type: string\n",
      "        description: The Notion page ID to read.\n",
      "      - name: notion_token\n",
      "        type: string\n",
      "        description: The user's Notion integration token.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "yaml_prompt = \"\"\"\n",
    "agent_instructions: |\n",
    "  You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
    "  - Provide clear, organized summaries of page content.\n",
    "  - Use the Notion API to fetch and display information.\n",
    "  - If a page cannot be read, explain the issue clearly.\n",
    "\n",
    "tools:\n",
    "  - name: notion_read_page_tool\n",
    "    description: >\n",
    "      Reads the content of a Notion page using its page ID and the user's Notion integration token.\n",
    "    parameters:\n",
    "      - name: page_id\n",
    "        type: string\n",
    "        description: The Notion page ID to read.\n",
    "      - name: notion_token\n",
    "        type: string\n",
    "        description: The user's Notion integration token.\n",
    "\"\"\"\n",
    "print(yaml_prompt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1ozm6Z467WQK"
   },
   "source": [
    "# Main"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 83
    },
    "id": "eNg-jwpx7X5s",
    "outputId": "4440b52a-46b3-4683-9183-13cd21596e25"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "### Notion Page Content\n",
       "*No content found or page is not accessible. Please check your page ID and sharing settings.*"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Define a wrapper to match the agent's expected tool signature\n",
    "def notion_tool_wrapper(inputs):\n",
    "    page_id = inputs.get(\"page_id\", \"\")\n",
    "    notion_token = inputs.get(\"notion_token\", \"\")\n",
    "    return notion_read_page_tool(page_id, notion_token)\n",
    "\n",
    "# Create the agent and register the tool\n",
    "agent = Agent(\n",
    "    instructions=\"\"\"\n",
    "    You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
    "    - Provide clear, organized summaries of page content.\n",
    "    - Use the Notion API to fetch and display information.\n",
    "    - If a page cannot be read, explain the issue clearly.\n",
    "    \"\"\",\n",
    "    tools={\n",
    "        \"notion_read_page_tool\": notion_tool_wrapper\n",
    "    }\n",
    ")\n",
    "\n",
    "# Call the tool directly (since agent.chat expects an LLM, but we want tool output)\n",
    "response = agent.execute_tool(\"notion_read_page_tool\", {\n",
    "    \"page_id\": page_id,\n",
    "    \"notion_token\": NOTION_API_KEY\n",
    "})\n",
    "\n",
    "# Check for error pattern and display a friendly message\n",
    "if response.startswith(\"Failed to fetch page content:\"):\n",
    "    display(Markdown(\"### Notion Page Content\\n*No content found or page is not accessible. Please check your page ID and sharing settings.*\"))\n",
    "else:\n",
    "    display(Markdown(f\"### Notion Page Content\\n{response}\"))"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
